#include "stdafx.h"
#include "RelevanceFeedbackManager.h"
#include <fstream>
#include "DocumentManager.h"
#include <algorithm>

bool RelevantData::isRelevantDocument(unsigned int documentIndex)
{
	for(std::vector<unsigned int>::iterator it = documentList.begin() ; it != documentList.end() ; it++)
	{
		if((*it) == documentIndex)
			return true;
		
		if((*it) > documentIndex)
			break;
	}
	
	return false;
}

RelevanceFeedbackManager::RelevanceFeedbackManager(DocumentManager& dm, std::string& filename)
{
	const int DOCUMENT_NAME_LENGTH = 13;
	//const int QUERY_INDEX_LENGTH = 3;

	std::ifstream file(filename);
	RelevantData* currentData = 0;
	while(file.good())
	{
		std::string line;
		std::getline(file, line);
		//file >> line;
		if(line.length() == DOCUMENT_NAME_LENGTH)
		{
			if(currentData == 0)
				currentData = new RelevantData();
			currentData->documentList.push_back(dm.GetDocumentIndex(line));
		}
		else// if(line.length() == QUERY_INDEX_LENGTH)
		{
			if(currentData != 0)
			{
				currentData->queryIndex = atoi(line.c_str());
				std::sort(currentData->documentList.begin(), currentData->documentList.end());
				relevantDataMap.insert(RelevantDataMap::value_type(currentData->queryIndex, currentData));
				currentData = 0;
			}
		}
	}

	file.close();
}

RelevanceFeedbackManager::~RelevanceFeedbackManager()
{
	for(RelevantDataMap::iterator it = relevantDataMap.begin() ; it != relevantDataMap.end() ; it++)
	{
		delete(it->second);
		it->second = 0;
	}
	relevantDataMap.clear();
}

RelevantData* RelevanceFeedbackManager::GetRelevantData(unsigned int index)
{
	RelevantDataMap::iterator it = relevantDataMap.find(index);
	if(it == relevantDataMap.end())
		return 0;

	return it->second;
}